//
//  WXPKTPTakePictureVC.m
//  拍照上传
//
//  Created by wxp on 2025/2/28.
//

#import "WXPKTPTakePictureVC.h"
#import "WXPKTPTakePictureLoadingView.h"

@interface WXPKTPTakePictureVC ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate,CAAnimationDelegate,AVCapturePhotoCaptureDelegate>

// 相机相关
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureDeviceInput *input;
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic, strong) AVCapturePhotoOutput *ImageOutPut;

// UI相关
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *leftShadowView;
@property (nonatomic, strong) UIView *rightShadowView;

// 按钮相关
@property (nonatomic, strong) UIButton *cancleButton;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, strong) UIButton *flashButton;
@property (nonatomic, strong) UIButton *reCamButton;
@property (nonatomic, strong) UIButton *photoButton;
@property (nonatomic, strong) UIButton *selectButton;

// 其他UI元素
@property (nonatomic, strong) UIImageView *faceKuangImage;
@property (nonatomic, strong) UIImageView *kuangImgView;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSDictionary *imageDict;
@property (nonatomic, strong) UIImageView *imagePhoto;

@property (nonatomic, strong) WXPKTPTakePictureLoadingView * uploadLoadingView;

@end

@implementation WXPKTPTakePictureVC

#pragma mark - lazy
- (AVCaptureVideoPreviewLayer *)previewLayer{
    if (_previewLayer == nil) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _previewLayer.frame = CGRectMake((SCREEN_WIDTH-Ratio(260))/2, (SCREEN_HEIGHT-Ratio(410))/2, Ratio(260), Ratio(410));
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    }
    return  _previewLayer;
}
- (AVCapturePhotoOutput *)ImageOutPut {
    if (!_ImageOutPut) {
        _ImageOutPut = [[AVCapturePhotoOutput alloc] init];
    }
    return _ImageOutPut;
}
// 初始化输入
- (AVCaptureDeviceInput *)input{
    if (_input == nil) {
        _input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    }
    return _input;
}
// 初始化输出
- (AVCaptureMetadataOutput *)output{
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc]init];
    }
    return  _output;
}
// 使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
- (AVCaptureDevice *)device{
    if (_device == nil) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}
- (UIView *)topView{
    if (!_topView ) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (SCREEN_HEIGHT-self.kuangImgView.height)/2)];
        _topView.backgroundColor = [UIColor colorWithHexString:@"4A4A4A" alpha:1];
        [_topView addSubview:self.cancleButton];
        UILabel * titleLabel = [UILabel new];
        titleLabel.fontNum = (17);
        titleLabel.textColor = COLOR_WHITE;
        [titleLabel fitTitle:@"INE" variable:0];
        titleLabel.centerXCenterY = XY(SCREEN_WIDTH/2, self.cancleButton.centerY);
        [_topView addSubview:titleLabel];
    }
    return _topView;
}
- (UIButton *)cancleButton{
    if (_cancleButton == nil) {
        _cancleButton = [UIButton new];
        _cancleButton.widthHeight = XY(BUTTON_HEIGHT, BUTTON_HEIGHT);
        _cancleButton.leftCenterY = XY(Ratio(12), [GlobalMethod getNavgationBarHeight]);
        [_cancleButton setImage:[UIImage imageNamed:@"icon-back-arrow-white"] forState:(UIControlStateNormal)];
        _cancleButton.tag = 1;
        [_cancleButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _cancleButton ;
}
- (UIView *)leftShadowView{
    if (_leftShadowView == nil) {
        _leftShadowView = [UIView  new];
        _leftShadowView.backgroundColor = self.topView.backgroundColor;
        _leftShadowView.widthHeight = XY((SCREEN_WIDTH-self.kuangImgView.width)/2+2, self.kuangImgView.height+20);
        _leftShadowView.leftTop = XY(-1, self.topView.bottom-10);
        UILabel *verticalLabel = [UILabel new];
        verticalLabel.textColor = COLOR_WHITE;
        [verticalLabel fitTitle:@"Coloque la parte delantera del lNE en el marco" variable:0];
        verticalLabel.transform = CGAffineTransformMakeRotation(M_PI_2);
        verticalLabel.centerXCenterY = XY(_leftShadowView.width/2, _leftShadowView.height/2);
        [_leftShadowView addSubview:verticalLabel];
    }
    return  _leftShadowView;
}
- (UIView *)rightShadowView{
    if (_rightShadowView == nil) {
        _rightShadowView = [UIView  new];
        _rightShadowView.backgroundColor = self.topView.backgroundColor;
        _rightShadowView.widthHeight = self.leftShadowView.widthHeight;
        _rightShadowView.rightCenterY = XY(SCREEN_WIDTH+1, self.leftShadowView.centerY);
    }
    return  _rightShadowView;
}
- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [UIView new];
        _bottomView.widthHeight = XY(SCREEN_WIDTH, (SCREEN_HEIGHT-self.kuangImgView.height)/2+1);
        _bottomView.leftBottom = XY(0, SCREEN_HEIGHT);
        _bottomView.backgroundColor = self.topView.backgroundColor;
        [_bottomView addSubview:self.photoButton];
        [_bottomView addSubview:self.reCamButton];
        [_bottomView addSubview:self.selectButton];
        [_bottomView addSubview:self.closeButton];
        [_bottomView addSubview:self.flashButton];
    }
    return _bottomView;
}
- (UIButton *)reCamButton
{
    if (_reCamButton == nil) {
        _reCamButton = [UIButton new];
        _reCamButton.widthHeight = XY(Ratio(80), BUTTON_HEIGHT);
        _reCamButton.leftCenterY = XY(30, self.photoButton.centerY);
        [_reCamButton setTitle:@"again" forState:UIControlStateNormal];
        _reCamButton.transform = CGAffineTransformMakeRotation(M_PI/2);
        [_reCamButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _reCamButton.hidden = true;
        WEAKSELF
        [_reCamButton setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
            // 重新拍照
            [NSObject clickFeedback];
            [weakSelf againPhotoClick];
        }];
    }
    return _reCamButton;
}
- (UIButton *)photoButton{
    if (_photoButton == nil) {
        _photoButton = [UIButton new];
        _photoButton.widthHeight = XY(Ratio(75), Ratio(75));
        _photoButton.centerXCenterY = XY(SCREEN_WIDTH/2, self.bottomView.height/2);
        [_photoButton setImage:[UIImage imageNamed:@"icon-KTP-take-picture"] forState: UIControlStateNormal];
        WEAKSELF
        [_photoButton setNoRepeatActionWithInterval:3 action:^(UIButton * _Nonnull button) {
            // 拍照
            [NSObject clickFeedback];
            [weakSelf.photoButton addClickAnimate];
            [weakSelf showLoadingView];
            [weakSelf takePicture];
        }];
    }
    return _photoButton;
}
- (UIButton *)selectButton{
    if (_selectButton == nil) {
        _selectButton = [UIButton new];
        _selectButton.widthHeight = XY(Ratio(80), BUTTON_HEIGHT);
        _selectButton.rightCenterY = XY(SCREEN_WIDTH-30, self.photoButton.centerY);
        [_selectButton setTitle:@"confirm" forState:UIControlStateNormal];
        _selectButton.transform = CGAffineTransformMakeRotation(M_PI/2);
        WEAKSELF
        [_selectButton setNoRepeatActionWithInterval:3 action:^(UIButton * _Nonnull button) {
            // 选择照片 返回上级
            [NSObject clickFeedback];
            [weakSelf confirmSelectPhoto];
        }];
        [_selectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _selectButton.hidden = true;
    }
    return _selectButton;
}
- (UIImageView *)faceKuangImage{
    if (_faceKuangImage == nil) {
        _faceKuangImage = [UIImageView new];
        _faceKuangImage.widthHeight = XY(Ratio(126), Ratio(129));
        _faceKuangImage.centerXCenterY = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
        _faceKuangImage.image = [UIImage imageNamed:@"icon-ktp-profile-picture"];
        _faceKuangImage.transform = CGAffineTransformMakeRotation(M_PI_2);
        _faceKuangImage.leftTop = XY(Ratio(27), Ratio(17));
    }
    return _faceKuangImage;
}
- (UIImageView *)kuangImgView{
    if (_kuangImgView == nil) {
        _kuangImgView = [UIImageView new];
        _kuangImgView.widthHeight = XY(Ratio(260), Ratio(410));
        _kuangImgView.centerXCenterY = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
        _kuangImgView.image = [UIImage imageNamed:@"icon-KTP-take-picture-border"];
    }
    return _kuangImgView;
}
- (UIButton *)closeButton
{
    if (_closeButton == nil) {
        _closeButton = [UIButton  new];
        _closeButton.widthHeight = XY(Ratio(50), Ratio(50));
        _closeButton.leftCenterY = XY((SCREEN_WIDTH-self.kuangImgView.width)/2-10, self.photoButton.centerY);
        [_closeButton setImage:[UIImage imageNamed:@"icon-KTP-camera-close"] forState:UIControlStateNormal];
        _closeButton.tag = 5;
        [_closeButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _closeButton;
}
- (UIButton *)flashButton
{
    if (_flashButton == nil) {
        _flashButton = [UIButton  new];
        _flashButton.widthHeight = XY(Ratio(50), Ratio(50));
        _flashButton.rightCenterY = XY(SCREEN_WIDTH-(SCREEN_WIDTH-self.kuangImgView.width)/2+10, self.photoButton.centerY);
        [_flashButton setImage:[UIImage imageNamed:@"icon-KTP-flashlight-open"] forState:UIControlStateSelected];
        [_flashButton setImage:[UIImage imageNamed:@"icon-KTP-flashlight-close"] forState:UIControlStateNormal];
        _flashButton.tag = 6;
        [_flashButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return  _flashButton;
}
- (WXPKTPTakePictureLoadingView *)uploadLoadingView
{
    if (_uploadLoadingView == nil) {
        _uploadLoadingView = [WXPKTPTakePictureLoadingView  new];
        _uploadLoadingView.leftTop = XY(0, 0);
    }
    return  _uploadLoadingView;
}
- (UIImageView *)imagePhoto
{
    if (_imagePhoto == nil) {
        _imagePhoto = [[UIImageView alloc]initWithFrame:self.previewLayer.frame];
        [_imagePhoto setContentMode:UIViewContentModeScaleAspectFill];
        _imagePhoto.userInteractionEnabled = true;
        _imagePhoto.clipsToBounds = YES;
        UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [_imagePhoto addGestureRecognizer:tapGestureRecognizer];
    }
    return _imagePhoto;
}
- (void)tapClick:(UITapGestureRecognizer * )tap{
    [self.imagePhoto removeFromSuperview];
}

#pragma mark - viewDidLoad
- (void)viewWillDisappear:(BOOL)animated{
    [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_TakePhotoPage action:KEY_OUT type:KEY_page];
}
- (void)viewWillAppear:(BOOL)animated{
    [GlobalMethod buryPointWithPageName:KEY_VerifyKtp featureName:KEY_TakePhotoPage action:KEY_ENTER type:KEY_page];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 打点
    self.view.backgroundColor = [UIColor clearColor];
    
    [self customCamera];
    
    [self.view addSubview:self.topView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.leftShadowView];
    [self.view addSubview:self.rightShadowView];
    [self.view addSubview:self.kuangImgView];
    [self.kuangImgView addSubview:self.faceKuangImage];
}

#pragma mark - 自定义相机
- (void)customCamera{
    [self showLoadingView];
    
    // 初始化会话
    self.session = [[AVCaptureSession alloc] init];
    [self configureSessionPreset];
    [self configureSessionInputOutput];
    [self configurePreviewLayer];
    
    // 异步启动相机
    [self startCameraSession];
    
    // 配置相机参数
    [self configureCameraSettings];
}

- (void)configureSessionPreset {
    if ([self.session canSetSessionPreset:AVCaptureSessionPresetPhoto]) {
        self.session.sessionPreset = AVCaptureSessionPresetPhoto;
    }
}

- (void)configureSessionInputOutput {
    NSError *error;
    // 配置输入
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error) {
        // NSLog(@"Error setting device input: %@", error);
        return;
    }
    // 添加输入
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    // 添加输出
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
        // 设置视频方向
        AVCaptureConnection *connection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
        if (connection.isVideoOrientationSupported) {
            connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        }
    }
}

- (void)configurePreviewLayer {
    [self.view.layer addSublayer:self.previewLayer];
}

- (void)startCameraSession {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.session startRunning];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.loadingView hideLoading];
        });
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Camera_Init extInfo:nil];
    });
}

- (void)configureCameraSettings {
    if ([self.device lockForConfiguration:nil]) {
        if ([self.device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [self.device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [self.device unlockForConfiguration];
    }
}

#pragma mark - 点击事件
- (void)btnClick:(UIButton *)sender{
    [NSObject clickFeedback];
    switch (sender.tag) {
        case 1:
        case 5:
        {
            // 取消，返回上级
            [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Cancel extInfo:nil];
            [self.session stopRunning];
            [Global_Nav popViewControllerAnimated:true];
        }
            break;
        case 6:
        {
            // 开启、关闭手电筒
            sender.selected = !sender.selected;
            [GlobalMethod toggleFlashlight];
        }
            break;
        default:
            break;
    }
}

#pragma mark -  拍照
// 重新拍照
- (void)againPhotoClick{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.session startRunning];
    });
    [self resetButtonStatusWithIsShow:true];
}

// 拍照
- (void)takePicture {
    // 确保会话在运行
    if (!self.session.isRunning) {
        NSLog(@"Camera session is not running!");
        return;
    }
    
    // 检查是否有活跃的视频连接
    AVCaptureConnection *videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection || !videoConnection.isEnabled) {
        NSLog(@"No active video connection!");
        return;
    }
    
    // 创建照片设置
    AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
    if ([self.device hasFlash]) {
        photoSettings.flashMode = AVCaptureFlashModeAuto;
    }
    
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Camera_Click extInfo:nil];
    
    // 捕获照片
    [self.ImageOutPut capturePhotoWithSettings:photoSettings delegate:self];
}

// 重置底部按钮状态
- (void)resetButtonStatusWithIsShow:(BOOL)isShowPhotoBtn
{
    if(isShowPhotoBtn){
        self.photoButton.hidden = false;
        self.reCamButton.hidden = true;
        self.selectButton.hidden = true;
    }else{
        self.photoButton.hidden = true;
        self.reCamButton.hidden = false;
        self.selectButton.hidden = false;
    }
    self.closeButton.hidden = !self.reCamButton.hidden;
    self.flashButton.hidden = self.closeButton.hidden;
}

// 确认选择照片
- (void)confirmSelectPhoto {
    // 打点
    // [GlobalMethod userBehaviorRecordWithPageName:@"VerifyKtp" action:@"ID_Front_Camera_Cope" extInfo:nil];
    // 上传
    [self requestOSSUploadPositive];
}

#pragma mark - 拍照防抖
- (void)configureCameraPreview:(AVCaptureDevice *)camera {
    for (AVCaptureConnection *connection in self.ImageOutPut.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
                if ([connection isVideoStabilizationSupported]) {
                    connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
                    NSLog(@"视频稳定已启用");
                } else {
                    NSLog(@"该设备的当前格式不支持视频稳定。");
                }
                break;
            }
        }
    }
}

#pragma mark - request
// 上传身份证正面并OCR
- (void)requestOSSUploadPositive{
    // 显示加载中
//    [self.view addSubview:self.uploadLoadingView];
//    [self.uploadLoadingView resetViewWithVerticalTitle:@"Cargando por favor espere"];
    [self showLoadingView];
    [RequestApi requestOSSUploadPositiveWithImage:self.image ocrPhotoChannel:0 delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        //返回的时候把图片传回去
        self.isIDFrontRetake = true;
        //ocr识别返回200 并且data.tongDunOCRResponseEntity.success为true则代表识别成功
        NSDictionary * data = [response dictionaryValueForKey:KEY_data];
        NSDictionary * entity = [data dictionaryValueForKey:KEY_tongDunOCRResponseEntity];
        BOOL isSuccess = [entity boolValueForKey:KEY_success];
        
        if (isSuccess) {
            // 只刷新了拍照的图片显示
            self.blockImage(self.image, true, self.isIDFrontRetake);
            if(self.blockIdentityInformation){
                self.blockIdentityInformation(data);
            }
        }else{
            // 只刷新了拍照的图片显示
            self.blockImage(self.image, false, self.isIDFrontRetake);
            if(self.blockAuthFail){
                self.blockAuthFail();
            }
            [GlobalMethod showAlert:@"Su foto no se puede detectar, por favor vuelva a tomar la foto"];
        }
        [self.loadingView hideLoading];
        [Global_Nav popViewControllerAnimated:true];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        // 提示
//        [self.uploadLoadingView removeFromSuperview];
        [self.loadingView hideLoading];
        [GlobalMethod showAlert:readStr(errorStr)];
        //返回的时候把图片传回去
        self.isIDFrontRetake = true;
        self.blockImage(self.image, false, self.isIDFrontRetake);
        if(self.blockAuthFail){
            self.blockAuthFail();
        }
        [Global_Nav popViewControllerAnimated:true];
    }];
}

#pragma mark - AVCapturePhotoCaptureDelegate
- (void)captureOutput:(AVCapturePhotoOutput *)output 
    didFinishProcessingPhoto:(AVCapturePhoto *)photo 
                     error:(NSError *)error {
    if (error) {
        NSLog(@"Error capturing photo: %@", error);
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Camera_End extInfo:@{@"isSuccess": [NSNumber numberWithBool:false]}];
        return;
    }
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Camera_End extInfo:@{@"isSuccess": [NSNumber numberWithBool:true]}];
    
    [self.session stopRunning];
    NSData *imageData = [photo fileDataRepresentation];
    if (imageData) {
        UIImage *capturedImage = [UIImage imageWithData:imageData];
        
        // 确保图片方向正确
        UIImageOrientation orientation = UIImageOrientationRight;
        self.image = [[UIImage alloc] initWithCGImage:capturedImage.CGImage
                                               scale:capturedImage.scale
                                         orientation:orientation];
        
        // 二次确认
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.session stopRunning];
//            [self.loadingView hideLoading];
//            [self resetButtonStatusWithIsShow:NO];
//        });
        
        // 打点
        [GlobalMethod hitPointWithPageName:KEY_VerifyKtp action:KEY_ID_Front_Camera_Cope extInfo:nil];
        
        // 上传
        [self.loadingView hideLoading];
        [self requestOSSUploadPositive];
    }
}

@end
